package com.koala.association;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.association.R;
import com.koala.data.AssoConnect;
import com.koala.data.Leaveword;
import com.koala.data.MyUtils;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * 
 */
public class LeaveWordFragment extends Fragment {
	private int GET=1;
	private int POST=2;
	private int MORE=3;
	private int FAULT=0;

	private ListView lv;
	private EditText liuyan;
	private ImageView iv_leaveword_commit;
	private String toUser;
	private String toId;
	private ArrayList<Leaveword> leavewords;
	private MyAdapter adapter;
	private boolean threadRunning;
	private boolean isEnd=false;

	Handler handler=new Handler(){;

	@Override
	public void handleMessage(Message msg){
		clearHuiFu();
		if(msg.what==GET){
			
			lv.setAdapter(adapter);
		}else if(msg.what==POST){
			getData();
		}else if(msg.what==MORE){
			if(leavewords!=null){
				adapter.notifyDataSetChanged();
			}

		}else {
			Log.w("Leave word ", "No msg return :"+msg.what); 
		}
	}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.fragment_leave_word, container, false);
		adapter=new MyAdapter();
		liuyan=(EditText) view.findViewById(R.id.leaveword_edit_content);
		iv_leaveword_commit=(ImageView)view.findViewById(R.id.iv_leaveword_commit);
		iv_leaveword_commit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(liuyan.getText().toString()==null||liuyan.getText().toString().equals("")){
					clearHuiFu(); 
					return;
				}
				String originInput = liuyan.getText().toString() ;

				final String content=originInput;
				Leaveword send=new Leaveword();
				send.setFromUserName(AssoConnect.getName());
				send.setToUserName(toUser);
				send.setFromId(toId);
				send.setContent(content);
				send.setTimeDetail(getTime());
				if(leavewords==null){
					leavewords=new ArrayList<Leaveword>();
				}
				leavewords.add(send);

				lv.setAdapter(adapter);
				lv.setSelection(leavewords.size()-1);
				new Thread(){
					public void run(){
						Message msg=new Message();
						msg.what=FAULT;
						if(AssoConnect.potLeaveword(content, toUser, toId)){
							msg.what=POST;
						}
						handler.sendMessage(msg);
					}
				}.start();
			}

			private String getTime() {
				Calendar c = Calendar.getInstance();
				int year, monthOfYear, dayOfMonth;
				year = c.get(Calendar.YEAR);
				monthOfYear = c.get(Calendar.MONTH);
				dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
				return ""+year+"/"+(monthOfYear+1)+"/"+dayOfMonth;
			}
		});
		lv=(ListView) view.findViewById(R.id.leaveword_message);
		lv.setOnScrollListener(new OnScrollListener() {
			private int scrollState;
			private int visibleItemCount;
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				this.scrollState = scrollState;
			}



			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if(isEnd)return;
				this.visibleItemCount = visibleItemCount;
				if (firstVisibleItem ==0) {


					new Thread(new Runnable() {

						@Override
						public void run() {
							if(threadRunning)return;
							threadRunning=true;
							Message msg = new Message();
							AssoConnect.nextLeaPno();
							ArrayList<Leaveword> l = AssoConnect.getLeaveword();
							if (AssoConnect.getMessage() == 1) {
								msg.what = MORE;
								try {
									if(l!=null){
										Collections.reverse(l);
										l.addAll(leavewords);
										leavewords=l;
									}
									Log.w("Get More Msg ","Leavewords size after Get More Thread Run >>>   " + leavewords.size()) ;
								} catch (Exception e) {
									e.printStackTrace();
								}

							} else {
								AssoConnect.lastLeaPno();
								msg.what = AssoConnect.getMessage();
								if(AssoConnect.getMessage() ==-27){
									isEnd=true;
								}
							}
							handler.sendMessage(msg);
							threadRunning=false;
						}
					}).start();
				}
			}
		});
		getData();
		return view;
	}

	private void clearHuiFu() {
		toUser=null;
		toId=null;
		liuyan.setText(null);
		liuyan.setHint(null);
	}

	public void onStart(){
		super.onStart();
		threadRunning=true;
	}

	@Override
	public void onPause(){
		super.onPause();
		threadRunning=false;
	}

	private void getData(){
		new Thread(){
			public void run(){
				Message msg=new Message();
				AssoConnect.resetLeaPno();
				isEnd=false;
				leavewords=AssoConnect.getLeaveword();
				if(AssoConnect.getMessage() == 1) {
					//leavewords=MyUtils.listConvert(leavewords);
					// 返回的留言是按时间从早到晚排序的，因此这里要反排序一下
					Collections.reverse(leavewords);
					msg.what = GET;
				} else {
					msg.what = AssoConnect.getMessage();
				}
				handler.sendMessage(msg);
			}
		}.start();
	}

	private class MyAdapter extends BaseAdapter{
		private LayoutInflater inflater;

		private int FROM_USER =0 ;
		private int TO_OTHER =1 ;
		public MyAdapter(){
			inflater=LayoutInflater.from(getActivity());
		}

		@Override
		public int getCount() {
			return leavewords.size();
		}

		@Override
		public Object getItem(int position) {
			return leavewords.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}


		@Override 
		public int getViewTypeCount(){
			return 2 ;
		}

		@Override 
		public int getItemViewType(int position){
			if(AssoConnect.getName().equals(leavewords.get(position).getFromUserName()))
				return FROM_USER;
			else return TO_OTHER;
		}




		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder =null;

			if(convertView==null){
				if(this.getItemViewType(position)==FROM_USER){

					convertView=inflater.inflate(R.layout.item_leaveword_from, null);
					holder = new ViewHolder() ;
					holder.name=(TextView) convertView.findViewById(R.id.chatfrom_name);
					holder.content=(TextView) convertView.findViewById(R.id.chatfrom_message);
					holder.time=(TextView)convertView.findViewById(R.id.chatfrom_sendtime);
					holder.message=(RelativeLayout) convertView.findViewById(R.id.chatfrom);
					convertView.setTag(R.id.FROM_USER, holder);


				}else if(this.getItemViewType(position)==TO_OTHER){

					convertView=inflater.inflate(R.layout.item_leaveword_to, null);
					holder = new ViewHolder() ;
					holder.name=(TextView) convertView.findViewById(R.id.chatto_name);
					holder.content=(TextView) convertView.findViewById(R.id.chatto_message);
					holder.time=(TextView)convertView.findViewById(R.id.chatto_sendtime);
					holder.message=(RelativeLayout) convertView.findViewById(R.id.chatto);
					convertView.setTag(R.id.TO_OTHER, holder);
				}

			} else {
				if(this.getItemViewType(position)==FROM_USER){
					holder = (ViewHolder)convertView.getTag(R.id.FROM_USER);
				}else if(this.getItemViewType(position)==TO_OTHER){
					holder = (ViewHolder)convertView.getTag(R.id.TO_OTHER);
				}
			}
			holder.name.setText(leavewords.get(position).getFromUserName());
			String text="";
			if(leavewords.get(position).getToUserName()!=null
					&&!leavewords.get(position).getToUserName().equals("")){
				text="回复："+leavewords.get(position).getToUserName()+" : ";
			}

			holder.content.setText(text + leavewords.get(position).getContent());  
			String td="";
			try{
				String[] t=leavewords.get(position).getTimeDetail().split("\\:");
				td=t[0]+":"+t[1];
			}catch(Exception e){
				e.printStackTrace();
			}
			holder.time.setText(td);

			final int index=position;
			holder.message.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					toUser=leavewords.get(index).getFromUserName();
					toId=leavewords.get(index).getFromId();
					liuyan.setText(null);
					liuyan.setHint("回复："+toUser);
				}
			});

			Log.w("Position : "+position+">>  Item Msg", ""+td +" : "+leavewords.get(position).getContent());
			return convertView;
		}


		class ViewHolder {
			private TextView name ;
			private TextView content ;
			private TextView time ;
			private RelativeLayout message ;
		}

	}

	void show(String s){
		Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT)
		.show();
	}

}
